package com.ruoyi.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSONUtil;
import com.ruoyi.common.core.domain.dto.VehicleInfoDTO;
import com.ruoyi.common.core.domain.dto.VehiclePicDTO;
import com.ruoyi.common.core.domain.dto.VehicleVideoDTO;
import com.ruoyi.common.utils.file.FileUtils;
import com.ruoyi.common.utils.sign.SM3Utils;
import com.ruoyi.config.QuUploadConfig;
import com.ruoyi.enums.DataTypeEnum;
import com.ruoyi.enums.PlateColorEnum;
import com.ruoyi.model.qu.QuUploadWeightReq;
import com.ruoyi.model.qu.QuUploadFileReq;
import com.ruoyi.model.qu.QuUploadFileRes;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * 上传文件接口-区平台
 */
@Slf4j
@Service
public class QuUploadService {

    @Autowired
    private QuUploadConfig uploadConfig;

    public boolean uploadWeight(VehicleInfoDTO vehicleInfo) {
        QuUploadWeightReq req = new QuUploadWeightReq();
        QuUploadWeightReq.data data = new QuUploadWeightReq.data();
        BeanUtil.copyProperties(vehicleInfo, data);
        data.setLaneNumber(vehicleInfo.getLaneNo());
        data.setPlateColor(PlateColorEnum.getEnumByLCode(vehicleInfo.getPlateColor()).getPColorCode());
        data.setCheckTime(DateUtil.format(DateUtil.parse(vehicleInfo.getCheckTime()), DatePattern.PURE_DATETIME_PATTERN));
        data.setUploadTime(DateUtil.format(new DateTime(), DatePattern.PURE_DATETIME_PATTERN));
        data.setTotal(vehicleInfo.getVehicleWeight());
        data.setOverRate(vehicleInfo.getLoadRate() * 100.0F);
        data.setVehicleType("1");
        List<QuUploadWeightReq.data> dataList = new ArrayList<>();
        dataList.add(data);
        req.setDataCount(1);
        req.setDataContent(dataList);
        String body = JSONUtil.toJsonStr(req);
        String url = uploadConfig.getUrl() + "/checkWeightData/upload";
        return this.post(url, body);

    }

    public boolean uploadPic(VehiclePicDTO dto) {
        String url = uploadConfig.getUrl() + "/attachmentFiles/upload";
        QuUploadFileReq.Data data = BeanUtil.copyProperties(dto, QuUploadFileReq.Data.class);
        String body = this.getUploadFileBody(data, dto.getFileFeature(), dto.getPlateColor(), dto.getCheckTime(), dto.getFileUrl());
        return this.post(url, body);
    }

    public boolean uploadVideo(VehicleVideoDTO dto) {
        String url = uploadConfig.getUrl() + "/attachmentFiles/upload";
        QuUploadFileReq.Data data = BeanUtil.copyProperties(dto, QuUploadFileReq.Data.class);
        String body = this.getUploadFileBody(data, DataTypeEnum.V.name(), dto.getPlateColor(), dto.getCheckTime(), dto.getFileUrl());
        return this.post(url, body);
    }

    public String getUploadFileBody(QuUploadFileReq.Data data, String fileFeature, Integer plateColor, Date checkTime, String fileUrl) {
        QuUploadFileReq fileProvinceReq = new QuUploadFileReq();
        data.setSiteCode(uploadConfig.getSiteCode());
        data.setDataType(DataTypeEnum.getCode(fileFeature));
        data.setPlateColor(PlateColorEnum.getEnumByLCode(plateColor).getPColorCode());
        data.setUploadTime(DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN));
        data.setDataLength(FileUtils.getFileLength(fileUrl));
        data.setDataContent(FileUtils.fileToBase64(fileUrl));
        data.setFileSize(Math.round(data.getDataLength() / 1024.0D * 100.0D) / 100.0D);
        List<QuUploadFileReq.Data> dataList = new ArrayList<>();
        dataList.add(data);
        fileProvinceReq.setDataCount(1);
        fileProvinceReq.setDataContent(dataList);
        return JSONUtil.toJsonStr(fileProvinceReq);
    }

    private boolean post(String url, String body) {
        String dataSM3 = SM3Utils.encrypt(body, uploadConfig.getSm3Key());
        Map<String, String> headerMap = new HashMap<>();
        headerMap.put("sysCode", uploadConfig.getSysCode());
        headerMap.put("distCode", uploadConfig.getDistCode());
        headerMap.put("dataAuth", uploadConfig.getDataAuth());
        headerMap.put("dataSM3", dataSM3);
        log.info("区平台-数据上传 地址：" + url);
        log.info("区平台-数据上传 头部：" + headerMap);
        HttpRequest httpRequest = HttpRequest.post(url).body(body).addHeaders(headerMap).timeout(1000);
        QuUploadFileRes quUploadFileRes;
        try (HttpResponse httpResponse = httpRequest.execute()) {
            log.info("区平台-数据上传 返回：" + httpResponse.body());
            quUploadFileRes = JSONUtil.toBean(httpResponse.body(), QuUploadFileRes.class);
            if (!quUploadFileRes.successYn()) {
                log.error("区平台-数据上传 报错: " + quUploadFileRes.getMessage());
            } else {
                log.info("区平台-数据上传 成功");
                return true;
            }
        } catch (Exception e) {
            log.error("区平台-数据上传 异常: " + e.getMessage());
        }
        return false;
    }
}